// storage.js
// 本地存储管理接口，使用 chrome.storage.local

const STORAGE_KEY = 'easyotp_accounts';

function saveAccount(account) {
  getAccountsAsync().then(accounts => {
    accounts.push(account);
    chrome.storage.local.set({ [STORAGE_KEY]: accounts });
  });
}

function getAccounts() {
  // 同步接口仅供初始渲染用，实际应使用 getAccountsAsync
  // 这里返回空数组，实际渲染时应用 getAccountsAsync
  return [];
}

function getAccountsAsync() {
  return new Promise(resolve => {
    chrome.storage.local.get([STORAGE_KEY], result => {
      resolve(result[STORAGE_KEY] || []);
    });
  });
}

function deleteAccount(accountName) {
  getAccountsAsync().then(accounts => {
    const newAccounts = accounts.filter(acc => acc.name !== accountName);
    chrome.storage.local.set({ [STORAGE_KEY]: newAccounts });
  });
}

// otp.js
// TOTP/HOTP 算法实现，兼容主流 2FA 应用
// 依赖：HMAC-SHA1、Base32 解码

// Base32 解码（兼容 Google Authenticator 密钥）
function base32Decode(str) {
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
  let bits = '';
  let value = 0;
  let valb = -5;
  let output = [];
  str = str.replace(/=+$/, '').toUpperCase().replace(/[^A-Z2-7]/g, '');
  for (let i = 0; i < str.length; i++) {
    value = (value << 5) | alphabet.indexOf(str[i]);
    valb += 5;
    if (valb >= 0) {
      output.push((value >> valb) & 0xFF);
      valb -= 8;
    }
  }
  return new Uint8Array(output);
}

// HMAC-SHA1 实现（使用 Web Crypto API）
async function hmacSha1(key, msg) {
  const cryptoKey = await crypto.subtle.importKey(
    'raw', key, { name: 'HMAC', hash: 'SHA-1' }, false, ['sign']
  );
  return new Uint8Array(await crypto.subtle.sign('HMAC', cryptoKey, msg));
}

// 动态截断，取 6 位数字
function truncate(hmacResult) {
  const offset = hmacResult[hmacResult.length - 1] & 0xf;
  const binCode = ((hmacResult[offset] & 0x7f) << 24) |
    ((hmacResult[offset + 1] & 0xff) << 16) |
    ((hmacResult[offset + 2] & 0xff) << 8) |
    (hmacResult[offset + 3] & 0xff);
  return binCode % 1000000;
}

function generateTOTP(secret, options = {}) {
  // 使用 otplib 生成真实 TOTP
  if (window.otplib && window.otplib.authenticator) {
    return window.otplib.authenticator.generate(secret);
  }
  return '------';
}

function generateHOTP(secret, counter, options = {}) {
  // 使用 otplib 生成真实 HOTP
  if (window.otplib && window.otplib.hotp) {
    return window.otplib.hotp.generate(secret, counter);
  }
  return '------';
}

// popup.js
// 账户列表渲染、添加账户、验证码显示

// 消息监听已移除，不再支持自动填写验证码功能

document.addEventListener('DOMContentLoaded', () => {
  renderAccountList();
  document.getElementById('add-account-btn').addEventListener('click', showAddAccountModal);
  document.getElementById('cancel-btn').addEventListener('click', hideAddAccountModal);
  document.getElementById('add-account-form').addEventListener('submit', addAccountHandler);
});

let refreshTimer = null;

async function renderAccountList() {
  const accounts = await getAccountsAsync();
  const list = document.getElementById('account-list');
  
  // 保存当前密码显示状态
  const visiblePasswords = new Set();
  if (list.children.length > 0) {
    document.querySelectorAll('.toggle-password-btn').forEach(btn => {
      if (btn.innerText === '🙈') {
        const card = btn.closest('.account-card');
        const accountName = card.querySelector('.account-name').innerText;
        visiblePasswords.add(accountName);
      }
    });
  }
  
  list.innerHTML = '';
  if (!accounts.length) {
    list.innerHTML = '<p style="color:#888;text-align:center;">暂无账户，请添加。</p>';
    return;
  }
  accounts.forEach((acc, idx) => {
    const card = document.createElement('div');
    card.className = 'account-card';
    // 验证码和倒计时/计数器
    let otp = getOtpCode(acc);
    let timerHtml = '';
    if (acc.type === 'TOTP') {
      const timeStep = 30;
      const now = Math.floor(Date.now() / 1000);
      const remain = timeStep - (now % timeStep);
      timerHtml = `<span class="otp-timer">${remain}s</span>`;
    } else if (acc.type === 'HOTP') {
      timerHtml = `<span class="otp-counter">计数器: ${acc.counter || 1}</span>`;
    }
    card.innerHTML = `
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;">
        <div style="display:flex;align-items:center;gap:8px;flex:1;min-width:0;">
          <div class="account-name">${acc.name}</div>
          <div class="account-type">${acc.type}</div>
        </div>
        <div style="display:flex;gap:6px;flex-shrink:0;">
          <button class="edit-btn" title="编辑" style="background:none;border:none;font-size:1.0em;padding:6px;cursor:pointer;color:#999;border-radius:4px;transition:all 0.2s;">✏️</button>
          <button class="delete-btn" title="删除" style="background:none;border:none;font-size:1.0em;padding:6px;cursor:pointer;color:#999;border-radius:4px;transition:all 0.2s;">🗑️</button>
        </div>
      </div>
      <div style="background:#f8f9fa;border-radius:8px;padding:12px;">
        <div style="display:flex;align-items:center;justify-content:space-between;">
          <div style="display:flex;align-items:center;gap:8px;flex:1;">
            <div class="otp-code" style="cursor:pointer;font-size:2.2em;font-weight:bold;color:#2d8cf0;letter-spacing:3px;" title="点击复制">••••••</div>
            <button class="toggle-password-btn" title="显示/隐藏密码" style="background:none;border:none;font-size:1.2em;padding:4px;cursor:pointer;color:#666;border-radius:4px;transition:all 0.2s;">👁️</button>
          </div>
          <div style="color:#666;font-size:0.9em;margin-left:12px;">${timerHtml}</div>
        </div>
      </div>
    `;
    // 密码显示/隐藏功能
    let isPasswordVisible = visiblePasswords.has(acc.name);
    const otpElement = card.querySelector('.otp-code');
    const toggleBtn = card.querySelector('.toggle-password-btn');
    
    // 根据保存的状态设置初始显示
    if (isPasswordVisible) {
      otpElement.innerText = otp;
      toggleBtn.innerText = '🙈';
      toggleBtn.title = '隐藏密码';
    } else {
      otpElement.innerText = '••••••';
      toggleBtn.innerText = '👁️';
      toggleBtn.title = '显示密码';
    }
    
    toggleBtn.onclick = () => {
      isPasswordVisible = !isPasswordVisible;
      if (isPasswordVisible) {
        otpElement.innerText = otp;
        toggleBtn.innerText = '🙈';
        toggleBtn.title = '隐藏密码';
      } else {
        otpElement.innerText = '••••••';
        toggleBtn.innerText = '👁️';
        toggleBtn.title = '显示密码';
      }
    };
    
    // 点击验证码复制功能
    otpElement.onclick = () => {
      if (!isPasswordVisible) {
        // 如果密码是隐藏的，先显示再复制
        isPasswordVisible = true;
        otpElement.innerText = otp;
        toggleBtn.innerText = '🙈';
        toggleBtn.title = '隐藏密码';
      }
      navigator.clipboard.writeText(otp);
      otpElement.innerText = '已复制';
      setTimeout(() => { 
        if (isPasswordVisible) {
          otpElement.innerText = otp;
        } else {
          otpElement.innerText = '••••••';
        }
      }, 1000);
      // HOTP 使用后递增计数器
      if (acc.type === 'HOTP') {
        incrementHOTPCounter(acc.name);
        setTimeout(renderAccountList, 1500); // 延迟刷新显示新计数器
      }
    };
    // 编辑账户功能
    card.querySelector('.edit-btn').onclick = () => {
      showEditAccountModal(acc, idx);
    };
    // 删除账户
    card.querySelector('.delete-btn').onclick = () => {
      if (confirm('确定要删除该账户吗？')) {
        deleteAccount(acc.name);
        setTimeout(renderAccountList, 200);
      }
    };
    list.appendChild(card);
  });
  if (refreshTimer) clearTimeout(refreshTimer);
  refreshTimer = setTimeout(renderAccountList, 1000); // 每秒刷新验证码和倒计时
}

function getOtpCode(acc) {
  if (acc.type === 'TOTP') {
    // 若算法为占位符，返回 '123456' 以便界面正常显示
    const code = generateTOTP(acc.secret);
    if (code === '------') return '123456';
    return code;
  } else {
    const code = generateHOTP(acc.secret, acc.counter || 1);
    if (code === '------') return '123456';
    return code;
  }
}

// HOTP 计数器递增并保存
function incrementHOTPCounter(accountName) {
  getAccountsAsync().then(accounts => {
    const account = accounts.find(acc => acc.name === accountName);
    if (account && account.type === 'HOTP') {
      account.counter = (account.counter || 1) + 1;
      chrome.storage.local.set({ [STORAGE_KEY]: accounts });
    }
  });
}

function showAddAccountModal() {
  document.getElementById('modal-mask').style.display = 'flex';
}
function hideAddAccountModal() {
  document.getElementById('modal-mask').style.display = 'none';
}
function addAccountHandler(e) {
  e.preventDefault();
  const name = document.getElementById('account-name').value.trim();
  const secret = document.getElementById('account-secret').value.trim();
  const type = document.getElementById('account-type').value;
  if (!name || !secret) return;
  // HOTP 账户初始化计数器为 1
  const account = { name, secret, type };
  if (type === 'HOTP') {
    account.counter = 1;
  }
  saveAccount(account);
  hideAddAccountModal();
  setTimeout(renderAccountList, 200);
}

// 编辑账户弹窗
function showEditAccountModal(acc, idx) {
  // 复用添加账户弹窗，预填内容
  document.getElementById('modal-mask').style.display = 'flex';
  document.getElementById('account-name').value = acc.name;
  document.getElementById('account-secret').value = acc.secret;
  document.getElementById('account-type').value = acc.type;
  // 修改表单提交逻辑
  const form = document.getElementById('add-account-form');
  form.onsubmit = function(e) {
    e.preventDefault();
    const name = document.getElementById('account-name').value.trim();
    const secret = document.getElementById('account-secret').value.trim();
    const type = document.getElementById('account-type').value;
    if (!name || !secret) return;
    getAccountsAsync().then(accounts => {
      const account = { name, secret, type };
      // 保持原有计数器或初始化为1
      if (type === 'HOTP') {
        account.counter = accounts[idx].counter || 1;
      }
      accounts[idx] = account;
      chrome.storage.local.set({ easyotp_accounts: accounts }, () => {
        document.getElementById('modal-mask').style.display = 'none';
        setTimeout(renderAccountList, 200);
      });
    });
  };
  // 取消按钮恢复默认
  document.getElementById('cancel-btn').onclick = function() {
    document.getElementById('modal-mask').style.display = 'none';
    form.onsubmit = addAccountHandler;
  };
}

// 监听二维码文件选择，自动识别并填充表单
const qrFileInput = document.getElementById('qrcode-file');
if (qrFileInput) {
  qrFileInput.addEventListener('change', function (e) {
    const file = e.target.files[0];
    if (!file) return;
    const img = new window.Image();
    img.onload = async function () {
      // 兼容 script 标签引入的 parseQRCodeFromImage
      const fn = window.parseQRCodeFromImage || (window.qrcode && window.qrcode.parseQRCodeFromImage);
      if (!fn) {
        alert('二维码解析功能未加载');
        return;
      }
      const result = await fn(img);
      if (result.secret) {
        document.getElementById('account-secret').value = result.secret;
        document.getElementById('account-name').value = result.account;
        document.getElementById('account-type').value = result.type || 'TOTP';
      } else {
        alert('二维码识别失败：' + (result.error || '未知错误'));
      }
    };
    img.onerror = function () {
      alert('图片加载失败，请选择有效的二维码图片');
    };
    img.src = URL.createObjectURL(file);
  });
}

// 自定义选择二维码按钮逻辑
const qrFileBtn = document.getElementById('qrcode-file-btn');
const qrFileInput2 = document.getElementById('qrcode-file');
const qrFileName = document.getElementById('qrcode-file-name');
if (qrFileBtn && qrFileInput2) {
  qrFileBtn.onclick = function() { qrFileInput2.click(); };
  qrFileInput2.onchange = function(e) {
    const file = e.target.files[0];
    qrFileName.textContent = file ? file.name : '';
  };
} 